package ar.com.photo_admin.domain

import grails.plugins.springsecurity.Secured

@Secured(["isAuthenticated()"])
class MessageController {

	def springSecurityService
	
	def userService
	
	def messageService
	
	static allowedMethods = [moveMessagesToTrash: "POST", deleteMessages: "POST", sendMessage: "POST"]
	
    def index() { 
		redirect(action: "received", params: params)
	}
	
	def show() {
		User user = springSecurityService.currentUser
		
		def sent = Message.sent(user).get(params.id)
		def received = Message.received(user).get(params.id)
		
		if (!sent && !received) {
			flash.error = message(code: 'messages.no.exist')
			redirect(action: "received")
			return
		}
		
		def msg = received ? received : sent
		
		if (received) {
			msg.userMessage.notified = true
			msg.save(flush:true)
		}
		
		[msg : msg, received : received]
	}
	
	def create() {
		Message message = new Message(params)
		UserMessage userMessage = new UserMessage(params)
		
		message.userMessage = userMessage
		
		[msg: message]
	}
	
	def received() {
		User user = springSecurityService.currentUser
		
		def messages = Message.received(user).list(getDefaultParams())
		
		render(view: "list", model: [messages : messages, received : true, action: 'received'])		
	}
	
	def sent() {
		User user = springSecurityService.currentUser
		
		def messages = Message.sent(user).list(getDefaultParams())
		
		render(view: "list", model: [messages : messages, sent : true, action: 'sent'])
	}
	
	def trash() {
		User user = springSecurityService.currentUser
		
		def messages = Message.trash(user).list(getDefaultParams())
				
		render(view: "list", model: [messages : messages, trash : true, action: 'trash'])
	}
	
	def getDefaultParams() {
		[max: 10, sort: 'dateCreated', order: 'desc', offset: params.offset]
	}
	
	def deleteReceivedMessages() {
		User user = springSecurityService.currentUser
		
		def selectedMessagesIds = getSelectedMessagesIds()
		def receivedMessages = Message.received(user).findAllByIdInList(selectedMessagesIds)
				
		receivedMessages.each { Message msg ->
			msg.userMessage.trash = true
			msg.save(flush:true)
		}
		
		def counter = receivedMessages.size()
		flash.message = counter == 1 ? message(code: 'messages.deleteReceivedMessages.single.success') : message(code: 'messages.deleteReceivedMessages.success', args: [counter])
		
		redirect(action: "received")
	}
	
	def deleteSentMessages() {
				
		User user = springSecurityService.currentUser
		
		def selectedMessagesIds = getSelectedMessagesIds()
		def messages = Message.sent(user).findAllByIdInList(selectedMessagesIds)
		
		def (messagesToDelete, messagesToMark) = messages.split { it.userMessage.deleted }
		
		messagesToMark.each { Message msg ->
			msg.deleted = true
			msg.save()
		}
		
		messageService.deleteMessage(messagesToDelete)
		
		def counter = messagesToDelete.size() + messagesToMark.size()
		flash.message = counter == 1 ? message(code: 'messages.deleteSentMessages.single.success') : message(code: 'messages.deleteSentMessages.success', args: [counter])	
		
		redirect(action: "sent")
	}
	
	def deleteTrashMessages() {
		
		User user = springSecurityService.currentUser
		
		def selectedMessagesIds = getSelectedMessagesIds()
		def messages = Message.trash(user).findAllByIdInList(selectedMessagesIds)
		
		def (messagesToDelete, messagesToMark) = messages.split { it.deleted }
		
		messagesToMark.each { Message msg ->
			msg.userMessage.deleted = true
			msg.save()
		}
		
		messageService.deleteMessage(messagesToDelete)
		
		def counter = messagesToDelete.size() + messagesToMark.size()
		flash.message = counter == 1 ? message(code: 'messages.deleteTrashMessages.single.success') : message(code: 'messages.deleteTrashMessages.success', args: [counter])
				
		redirect(action: "trash")
	}
	
	def restoreMessages() {
		User user = springSecurityService.currentUser
		
		def selectedMessagesIds = getSelectedMessagesIds()
		def receivedMessages = Message.trash(user).findAllByIdInList(selectedMessagesIds)
				
		receivedMessages.each { Message msg ->
			msg.userMessage.trash = false
			msg.save(flush:true)
		}
		
		def counter = receivedMessages.size()
		flash.message = counter == 1 ? message(code: 'messages.restoreMessages.single.success') : message(code: 'messages.restoreMessages.success', args: [counter])
		
		redirect(action: "received")
	}
	
	def getSelectedMessagesIds() {
		params.entrySet().findAll {
			it.key.startsWith("message_")
		 }.collect {
			 it.key.split("message_")[1].toLong()
		 }
	}
	
	def sendMessage() {
		
		String subject = params.subject
		String body = params.message
		
		if (!subject)
			subject = message(code: "messages.no.subject")
		
		User from = springSecurityService.currentUser
		User to = null
		
		if (params.to != null && params.to.toString() != "") {
			to = userService.loadUserFromAutocompleteText(params.to.toString())
			
			if (!to) {
				flash.error = message(code: 'client.doesnot.exist')
				render(view: "create", model: [msg: new Message(params)])
				return
			}
		}
		
		def sendMessage = messageService.sendMessage(subject, body, from, to)
		
		flash.message = message(code: "messages.sent.success")
		
		redirect(controller: "message", action: "show", id: sendMessage.id)
	}
}
